import { menuDeleteMenuIdApi, menuTreeApi } from '@/apis/payment'
import { MenuTreeVO } from '@/apis/payment.type'
import BasicPage from '@/components/BasicPage'
import { BasicTable, useTable } from '@/components/BasicTable'
import { PlusOutlined } from '@ant-design/icons'
import { ProColumns } from '@ant-design/pro-components'
import { Button } from 'antd'
import UpdateMenuModal from './components/UpdateMenuModal'
import { useModal } from '@/components/BasicModal'
import useConfirm from '@/hooks/useConfirm'
import useMessage from '@/hooks/useMessage'

export default function MenuManagement() {
  const { message } = useMessage()
  const { deleteConfirm } = useConfirm()
  const { tableAction, getProTableResponse } = useTable()
  const [registerUpdateMenuModal, { openModal: openUpdateMenuModal }] = useModal()

  const columns: ProColumns<MenuTreeVO>[] = [
    {
      title: '菜单名称',
      dataIndex: 'menuName',
      key: 'menuName',
      hideInSearch: false // 在搜索栏中显示
    },
    {
      title: '菜单类型',
      dataIndex: 'menuType',
      key: 'menuType',
      hideInSearch: true, // 在搜索栏中显示
      valueEnum: {
        // 假设菜单类型有几种固定的值
        M: { text: '目录' },
        C: { text: '菜单' },
        F: { text: '按钮' }
      }
    },
    {
      title: '排序',
      dataIndex: 'menuSort',
      key: 'menuSort',
      hideInSearch: true // 不在搜索栏中显示
    },
    {
      title: '操作',
      valueType: 'option',
      width: 100,
      fixed: 'right',
      render: (_, record) => [
        <a key="edit" onClick={() => openUpdateMenuModal(record)}>
          编辑
        </a>,
        <a key="delete" className="delete" onClick={() => onDeleted(record)}>
          删除
        </a>
      ]
    }
  ]

  async function getMenuList() {
    const resp = await menuTreeApi({})
    return getProTableResponse(resp)
  }

  function tableReflesh() {
    tableAction.current?.reload()
  }

  function onDeleted(record?: MenuTreeVO) {
    deleteConfirm({
      onOk: async () => {
        if (!record) return message.warning('请选择要删除的数据')
        const { success } = await menuDeleteMenuIdApi({ menuId: record.menuId as number })
        if (success) {
          message.success('删除成功')
          tableReflesh()
        }
      }
    })
  }

  return (
    <BasicPage>
      <BasicTable
        request={getMenuList}
        proTableProps={{
          columns,
          rowKey: 'menuId',
          headerTitle: '菜单列表',
          actionRef: tableAction,
          toolBarRender: () => [
            <Button type="primary" icon={<PlusOutlined />} onClick={() => openUpdateMenuModal()}>
              新增菜单
            </Button>
          ]
        }}
      />

      <UpdateMenuModal register={registerUpdateMenuModal} onFinished={tableReflesh} />
    </BasicPage>
  )
}
